//Sat Jul 17 20:35:41 CDT 2010
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cctype>
#include <string>
#include <cstring>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>

using namespace std;

class MatrixShiftings
{
public:
	int minimumShifts(vector<string> matrix, int value)
	{
		int M = matrix.size();
		int N = matrix[0].size();
		int ret = M + N;
		for (int i = 0; i < M; i++)
		{
			for (int j = 0; j < N; j++)
			{
				if (matrix[i][j] - '0' == value)
				{
					ret = min(ret, i + j);
					ret = min(ret, i + N - j);
					ret = min(ret, M - i + j);
					ret = min(ret, M - i + N - j);
				}
			}
		}
		return ret == (M + N) ? -1 : ret;
	}
};
